/*
 * Mutex.cpp
 *
 *  Created on: Mar 15, 2011
 *      Author: user
 */

#include "bilbao/lang/Mutex.h"

namespace bilbao
{
	namespace lang
	{
	// --------------------------------------------------------------------
	// Mutex
	// --------------------------------------------------------------------
	Mutex::Mutex(void)
		: locked(false)
	{
	#if BILBAO_PLATAFORM == BILBAO_WIN32
		mutex = CreateMutex (0, false, 0);
	#else
		pthread_mutex_init (&mutex, 0);
	#endif
	}
	// --------------------------------------------------------------------
	Mutex::~Mutex(void)
	{
	#if BILBAO_PLATAFORM == BILBAO_WIN32
		CloseHandle (mutex);
	#else
		pthread_mutex_destroy (&mutex);
	#endif
	}
	// --------------------------------------------------------------------
	void Mutex::lock(void)
	{
	#if BILBAO_PLATAFORM == BILBAO_WIN32
		if( WaitForSingleObject (mutex, INFINITE) == WAIT_FAILED)
		{
			//TODO: LOG!
			//LOG("Couldn't lock mutex");
		}
	#else
		pthread_mutex_lock (&mutex);
	#endif

		locked = true;
	}
	// --------------------------------------------------------------------
	void Mutex::unlock(void)
	{
	#if BILBAO_PLATAFORM == BILBAO_WIN32
		ReleaseMutex (mutex);
	#else
		pthread_mutex_unlock (&mutex);
	#endif

		locked = false;
	}
	// --------------------------------------------------------------------
	bool Mutex::isLocked(void) const
	{
		return locked;
	}
	// --------------------------------------------------------------------
	// MutexLocker
	// --------------------------------------------------------------------
	MutexLocker::MutexLocker( Mutex& m )
		: mutex(m)
	{
		mutex.lock();
	}
	// --------------------------------------------------------------------
	MutexLocker::~MutexLocker()
	{
		mutex.unlock();
	}
	// --------------------------------------------------------------------
	}
}
